package com.fl.iocaop.java8;

import org.junit.Test;

import java.util.*;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class FilterClass {
    private static List<apple> apples = new ArrayList<>();
    //为apple集合注入值
    static {
        apples.add(new apple("黄色",50, apple.status.FREE));
        apples.add(new apple("绿色",60,apple.status.FREE));
        apples.add(new apple("嘿色",60,apple.status.SUCCESSF));
        apples.add(new apple("红色",85,apple.status.SUCCESSF));
        apples.add(new apple("白色",100,apple.status.FULL));
    }

    //利用设计的方法提取后判断苹果重量
    //大于50过滤添加至新集合
    public List<apple> filterapple(List<apple> list, FilterAppleByWeigth<apple> filter){
        List<apple> apples = new ArrayList<>();
        for (apple apple : list) {
           if (filter.FilterApple(apple)){
               apples.add(apple);
           }
        }
        return  apples;
    }
    //使用策略设计模式优化
    @Test
    public void test(){
        List<apple> list = filterapple(apples, new FileterApple());
        for (apple apple : list) {
            System.out.println(apple.toString());
        }
    }
    //使用lanmbda表达式优化
    @Test
    public void test2(){
//        List<apple> apples = new FilterClass().filterapple(FilterClass.apples, (e) -> e.getWeight() >= 60);
//        apples.forEach(System.out::println);
        List<apple> list = apples.stream().filter((e) -> e.getWeight() >= 60 && e.getWeight() < 100)
                .limit(5).collect(Collectors.toList());
        list.stream()
                .map(apple::getColor)
                .forEach(System.out::println);
        Consumer<String>  con = (s)-> System.out.println(s);
        con.accept("我看你嘛呢");

    }
    //含有多个参数，且多条语句的lambda表达式写法
    @Test
    public void test3(){
        //比较两数大小方法
        Comparator<Integer> com = (x,y)->{
            System.out.println("执行大小比较！");
            return Integer.compare(x,y);
        };
    }

    @Test
    public void test4(){
        Comparator<Integer> com = (x,y)->Integer.compare(x,y);
        System.out.println(com.compare(2, 1));
    }

    //判断两个苹果重量是否相同，相同再按颜色排名
    @Test
    public void test5(){
        Collections.sort(apples,(a1,a2)->{
            if (a1.getWeight()==a2.getWeight()){
                return a1.getColor().compareTo(a2.getColor());
            }else {
                return Integer.compare(a1.getWeight(),a2.getWeight());
            }
        });

        apples.forEach(System.out::println);
    }

    public String StringHanlder(String str ,Function function){
        return function.getValue(str);
    }
    //函数式接口的使用
    @Test
    public void test6(){
        //小写转大写
        System.out.println(StringHanlder("acasds", (s) -> s.toUpperCase(Locale.ROOT)));

        //字符串截取
        System.out.println(StringHanlder("我来了你好吗", (str) -> str.substring(2, 6)));
    }
}
